package dataStructs.linklist;

/**
 * @author Jonny Long
 * @date 2021/3/7 9:15
 * 以下单链表带有头节点
 */
public class SingleLinkedList {
    // 初始化头节点
    private Node head = new Node(0, "");

    // 返回头节点
    public Node getHead() {
        return head;
    }

    // 链表长度
    public static int getLength(Node head) {
        if (head.next == null) {
            return 0;
        }
        Node cur = head.next;
        int length = 0;
        while (cur != null) {
            cur = cur.next;
            length++;
        }
        return length;
    }

    // 遍历链表
    public void list() {
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        Node temp = head.next;
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    // 头插法
    public void insertFirst(Node node) {
        node.next = head.next;
        head.next = node;
    }

    // 尾插法
    public void append(Node node) {
        Node temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = node;
    }

    // 插入到指定位置
    public void insertPos(Node node, int pos) {
        Node temp = head;
        while (temp.next != null && pos != 0) {
            temp = temp.next;
            pos--;
        }
        node.next = temp.next;
        temp.next = node;
    }

    // 修改节点信息
    public void update(Node newNode) {
        //判断是否空
        if (head.next == null) {
            System.out.println("链表为空，更新失败");
        }
        Node temp = head.next;
        while (temp != null) {
            if (temp.no == newNode.no) {
                temp.name = newNode.name;
                return;
            }
            temp = temp.next;
        }
        System.out.println("没有找到该节点");
    }

    // 删除节点
    public void del(int no) {
        Node temp = head;
        while (temp.next != null) {
            if (temp.next.no == no) {
                temp.next = temp.next.next;
                return;
            }
            temp = temp.next;
        }
        System.out.println("没有找到该节点");
    }

    // 单链表翻转
    public static void reverseList(Node head) {
        if (head.next == null || head.next.next == null) {
            return;
        }
        Node cur = head.next;
        Node p;
        // 断开头节点与链表主体的连接
        head.next = null;
        while (cur != null) {
            p = cur.next;
            cur.next = head.next;
            head.next = cur;
            cur = p;
        }
    }
}
